package com.mobilesales.android.activities.tasks;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.activities.ModelActivity;
import com.mobilesales.android.adapters.CalendarAdapter;
import com.mobilesales.android.database.TaskManager;
import com.mobilesales.android.model.tasks.CyclicTask;
import com.mobilesales.android.model.tasks.Schedule;
import com.mobilesales.android.model.tasks.Task;
import com.mobilesales.android.util.DateUtil;
import com.mobilesales.android.util.MessageBox;
import com.mobilesales.android.util.Settings;

public class Tasks extends ModelActivity<Tasks> {

	private GridView calGridView;
	private Calendar calendar;
	private TextView currentMonthLbl;

	private List<Task> tasks;
	private List<CyclicTask> cyclicTasks;
	private int employeeId = 0;
	
	private Handler handler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tasks);
		calGridView = (GridView) this.findViewById(R.id.calendar);
		currentMonthLbl = (TextView) this.findViewById(R.id.currentMonth);
		calendar = Calendar.getInstance();
		Settings s = Settings.getSettings();
		if (s!=null)
			employeeId = s.getEmployeeId();
		Log.i(this.getClass().toString(), "employeeId:"+employeeId);
		
		this.loadItems();
	}

	private void loadItems() {
		tasks = this.getTasks(employeeId);
		cyclicTasks = this.getCyclicTasks(employeeId);
		Log.i("cyclicTaskCount", cyclicTasks.size()+"");
		drawCalendar(calendar);		
	}

	public void prevMonth(View v) {
		calendar.add(Calendar.MONTH, -1);
		this.drawCalendar(calendar);
	}

	public void nextMonth(View v) {
		calendar.add(Calendar.MONTH, 1);
		this.drawCalendar(calendar);
	}

	private void drawCalendar(Calendar calendar) {
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);

		int[] monthNameResIds = DateUtil.monthNamesStringResourceIds();

		currentMonthLbl.setText(String.format("%s %d",
				this.getString(monthNameResIds[month]), year));
		List<Integer> occupiedDays = new ArrayList<Integer>();
		if (cyclicTasks != null && tasks != null) {
			occupiedDays = this.tasksToOccupiedDays(year, month, cyclicTasks,
					tasks);
		} else {
			MessageBox.show(this, getString(R.string.ErrorTaskList));
		}
		CalendarAdapter adapter = CalendarAdapter.generateAdapter(this, year,
				month + 1, occupiedDays);
		calGridView.setAdapter(adapter);
	}

	private List<CyclicTask> getCyclicTasks(int employeeId) {
		TaskManager manager = new TaskManager(this);
		List<CyclicTask> tasks = manager.GetCyclicTaskList(employeeId);
		manager.Close();
		return tasks;
	}

	private List<Task> getTasks(int employeeId) {
		List<Task> tasks = null;
		TaskManager manager = new TaskManager(this);
		List<Schedule> schedules = manager.GetScheduleList(employeeId);
		if (schedules != null) {
			tasks = new ArrayList<Task>();
			for (Schedule s : schedules) {
				List<Task> stasks = manager.GetTaskList(s.Id);

				if (stasks != null) {
					Log.i("getTasks", "count:" + stasks.size() + " sid:" + s.Id);
					tasks.addAll(stasks);
				} else {
					tasks = null;
					break;
				}
			}
		}
		manager.Close();
		return tasks;
	}

	private List<Integer> tasksToOccupiedDays(int year, int month,
			List<CyclicTask> cyclicTasks, List<Task> tasks) {
		List<Integer> occupied = new ArrayList<Integer>();
		GregorianCalendar calendar = new GregorianCalendar(year, month, 1);
		int dayInMonths = calendar
				.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

		if (cyclicTasks != null) {
			for (CyclicTask tsk : cyclicTasks) {
				Date date = DateUtil.parseDate(tsk.StartTime);
				calendar.setTime(date);

				GregorianCalendar current = new GregorianCalendar(year, month,
						1);
				for (int i = 1; i <= dayInMonths; i++) {
					current.set(year, month, i);
					current.set(GregorianCalendar.HOUR_OF_DAY,
							calendar.get(GregorianCalendar.HOUR_OF_DAY));
					current.set(GregorianCalendar.MINUTE,
							calendar.get(GregorianCalendar.MINUTE));

					long diff = Math.abs(current.getTimeInMillis()
							- calendar.getTimeInMillis())
							/ (24 * 60 * 60 * 1000);

					if (diff % tsk.TaskInterval == 0) {
						if (!occupied.contains(i))
							occupied.add(i);
					}
				}

			}
		}

		if (tasks != null) {
			for (Task tsk : tasks) {
				Date date = DateUtil.parseDate(tsk.StartTime);
				calendar = new GregorianCalendar();
				calendar.setTime(date);
				
				if (calendar.get(GregorianCalendar.YEAR) == year
						&& calendar.get(GregorianCalendar.MONTH) == month) {
					int day = date.getDate();

					Log.i("day", day+"");
					if (!occupied.contains(day))
						occupied.add(day);
				}
			}
		}
		return occupied;
	}

	public void refresh() {
		handler.post(new Runnable() {
			public void run() {
				loadItems();
			}
		});
	}

}
